package cn.xxc.user.service.impl;

import cn.xxc.basic.constant.WxConstants;
import cn.xxc.basic.dto.LoginDto;
import cn.xxc.basic.exception.BusinessException;
import cn.xxc.basic.jwt.JwtUtils;
import cn.xxc.basic.jwt.LoginData;
import cn.xxc.basic.jwt.RsaUtils;
import cn.xxc.basic.util.AjaxResult;
import cn.xxc.basic.util.HttpUtil;
import cn.xxc.basic.util.Md5Utils;
import cn.xxc.basic.util.StrUtils;
import cn.xxc.system.domain.Menu;
import cn.xxc.system.mapper.MenuMapper;
import cn.xxc.system.mapper.PermissionMapper;
import cn.xxc.user.domain.Logininfo;
import cn.xxc.user.domain.User;
import cn.xxc.user.domain.Wxuser;
import cn.xxc.user.mapper.LogininfoMapper;
import cn.xxc.user.mapper.UserMapper;
import cn.xxc.user.mapper.WxuserMapper;
import cn.xxc.user.service.ILogininfoService;
import cn.xxc.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 * 1.账号登录
 * 2.微信登录
 *  2.1.微信绑定
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;


    /**
     * 账户登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        //一：校验 - 空值校验
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
            throw new BusinessException("信息不能为空!");
        }
        //二：校验 - 账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号或密码错误!!!");
        }
        //三：校验 - 密码 - 加密加盐
        //前端输入的密码进行加密加盐
        String inputPwd= Md5Utils.encrypByMd5(loginDto.getCheckPass()+logininfo.getSalt());
        if (!inputPwd.equals(logininfo.getPassword())) {
            throw new BusinessException("账号或密码错误!!!");
        }
        //四：校验 - 是否被禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    /**
     * 第三方微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        //获取微信access_token和openid
        String url=WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String httpGet = HttpUtil.httpGet(url);
        //阿里巴巴的fastJson将json格式的字符串转成json对象
        JSONObject jsonObject= JSONObject.parseObject(httpGet);
        //从json对象中获取属性名
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
       //判断微信是否登录过，登录过直接登录，没有登录则进行绑定在登录
        Wxuser wxuser=wxuserMapper.loadByopenid(openid);
        if (wxuser != null) {
            User user = userMapper.loadByid(wxuser.getUserId());
            if (user != null) {
                Logininfo logininfo = logininfoMapper.loadByid(user.getLogininfoId());
                //五：生成token，并将登录信息保存到redis数据库，设置30有效
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        return AjaxResult.me().setSuccess(false).setResultObj("?access_token="+access_token+"&openid="+openid);
    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    @Transactional
    public AjaxResult binder(Map<String, String> map) {
        String phone=map.get("phone");
        String verifyCode=map.get("verifyCode");
        String access_token=map.get("access_token");
        String openid=map.get("openid");
       //1.空值校验
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空！");
        }

        //2.校验手机验证码
        Object o = redisTemplate.opsForValue().get("binder:" + phone);
        if (o == null) {
            throw new BusinessException("验证码过期!");
        }
        if (!verifyCode.equals(o.toString().split(":")[0])) {
            throw new BusinessException("验证码错误!");
        }
        //3.获取微信信息
        String url=WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        String httpGet = HttpUtil.httpGet(url);
        //阿里巴巴的fastJson将json格式的字符串转成json对象
        JSONObject jsonObject= JSONObject.parseObject(httpGet);
        //防止微信重复绑定
        wxuserMapper.delByopenid(openid);
        //4.添加数据到数据库
        Wxuser wxuser=fastJsonToUser(jsonObject);
        User user = getUser(phone);
        Logininfo logininfo = UserToLogininfo(user);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        Map<String, Object> maps = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(maps);
    }

    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>();
        //细节：如果是管理员才需要加四个数据，如果是用户只需要：登录信息对象，jwt串【1,4】
        //一：想办法获取四个数据
        //1.登录信息对象 - 在参数中
        map.put("logininfo",logininfo);
        LoginData loginData=new LoginData();
        loginData.setLogininfo(logininfo);
        if (logininfo.getType()==0){///后台管理员
            //2.当前登录人的所有权限的sn集合 - 昨天写过了 - 直接调用方法
            List<String> permissions = permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //3.当前登录人的所有二级菜单及其它的父级菜单【前端需要】 - 自己写 - 难点1
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //4.将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
        PrivateKey privateKey = null;
        try {
            privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间
        //二：将四个数据装到map进行返回。疑问：jwt串里面不是已经有登录信息，权限和菜单了吗？ - 前端没有做解密
        map.put("token",jwtToken);

        return map;
    }

    private  Wxuser fastJsonToUser(JSONObject jsonObject){
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    private User getUser(String phone){
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        user.setSalt(StrUtils.getComplexRandomString(32));
        user.setPassword(Md5Utils.encrypByMd5(StrUtils.getComplexRandomString(6)+user.getSalt()));
        user.setState(1);
        return user;
    }

    private Logininfo UserToLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }

}
